/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * listSubSetor.java
 *
 * Created on 28/11/2011, 12:21:53
 */
package visao;

import fachada.FachadaBDR;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import setor.Setor;
import subSetor.SubSetor;
import util.ErroAcessoRepositorioException;
import util.KeyValue;

/**
 *
 * @author amedeiros
 */
public class listSubSetor extends javax.swing.JFrame {
    public String[] titulos = new String [] {"#", "Descrição Sub Setor", "Setor", "QTD Maxima", "QTD Minima", "QTD Atual", "Status"};
    public DefaultTableModel defTable;
    public CadSubSetor cadastroSubSetor = new CadSubSetor();
    
    /** Creates new form listSubSetor */
    public listSubSetor() {
        
        try {
            FachadaBDR objFachadaBDR = FachadaBDR.getInstancia();
            List<SubSetor> listSubSetor = objFachadaBDR.listarSubSetorAtivos();
            // Setando a tabela
            this.defTable =  atualizaLista(listSubSetor);

        }  catch (ErroAcessoRepositorioException ex) {
            System.out.println(ex.getMessage());
        }catch(Exception e){
            System.out.println(e.getMessage());
        }
        initComponents();
        this.setLocationRelativeTo(null);
        this.setIconImage(new ImageIcon(getClass().getResource("/Imagens/visao.gif")).getImage());
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel_idSetor = new javax.swing.JLabel();
        jComboBox_idSetor = new javax.swing.JComboBox();
        jTextField_DescricaoSetor = new javax.swing.JTextField();
        jLabel_Nome = new javax.swing.JLabel();
        jButton_Buscar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton_Cadastrar = new javax.swing.JButton();
        jButton_Editar = new javax.swing.JButton();
        jButton_Atualizar = new javax.swing.JButton();
        jButton_Remover = new javax.swing.JButton();
        mensagem = new javax.swing.JLabel();

        setTitle("SubSetor");
        setResizable(false);

        jLabel_idSetor.setText("Setor :");

        try {
            FachadaBDR objFachadaBDR = FachadaBDR.getInstancia();

            List<Setor> listSetor = objFachadaBDR.listarSetor("");

            jComboBox_idSetor.addItem(new KeyValue("--- Favor Selecionar ---","0"));
            for (Setor objSetor : listSetor) {
                jComboBox_idSetor.addItem(new KeyValue(objSetor.getDescricaoSetor(), Integer.toString(objSetor.getIdSetor())));
            }

        } catch (Exception e) {
        }

        jLabel_Nome.setText("Descrição Sub Setor:");

        jButton_Buscar.setText("Buscar");
        jButton_Buscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_BuscarActionPerformed(evt);
            }
        });

        jTable1.setModel(this.defTable);
        jScrollPane1.setViewportView(jTable1);

        jButton_Cadastrar.setText("Cadastrar");
        jButton_Cadastrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_CadastrarActionPerformed(evt);
            }
        });

        jButton_Editar.setText("Editar");
        jButton_Editar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_EditarActionPerformed(evt);
            }
        });

        jButton_Atualizar.setText("Atualizar");
        jButton_Atualizar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_AtualizarActionPerformed(evt);
            }
        });

        jButton_Remover.setText("Remover");
        jButton_Remover.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_RemoverActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel_Nome, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel_idSetor, javax.swing.GroupLayout.Alignment.TRAILING))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jTextField_DescricaoSetor, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jButton_Buscar, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jComboBox_idSetor, javax.swing.GroupLayout.PREFERRED_SIZE, 276, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(mensagem, javax.swing.GroupLayout.DEFAULT_SIZE, 686, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton_Cadastrar, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jButton_Editar, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jButton_Atualizar, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jButton_Remover, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 686, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(31, 31, 31)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel_Nome)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jComboBox_idSetor, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel_idSetor))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jTextField_DescricaoSetor, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jButton_Buscar))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 364, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(33, 33, 33)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton_Cadastrar)
                    .addComponent(jButton_Editar)
                    .addComponent(jButton_Atualizar)
                    .addComponent(jButton_Remover))
                .addGap(18, 18, 18)
                .addComponent(mensagem, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void jButton_CadastrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_CadastrarActionPerformed
     try {
            if(!this.cadastroSubSetor.isVisible()){
                this.cadastroSubSetor = new CadSubSetor();
                this.cadastroSubSetor.setVisible(true);
            }
            FachadaBDR objfaFachadaBDR = FachadaBDR.getInstancia();
            List<SubSetor> listSubSetor = objfaFachadaBDR.listarSubSetorAtivos();

            // Setando a tabela
            this.defTable =  atualizaLista(listSubSetor);

            // Setando a nova listagem
            jTable1.setModel(this.defTable);

            jTable1.revalidate();
            mensagem.setText("");
        } catch (Exception ex) {
            mensagem.setText(ex.getMessage());
        }
}//GEN-LAST:event_jButton_CadastrarActionPerformed

private void jButton_BuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_BuscarActionPerformed
    try {
        // instanciando a fachada
        FachadaBDR objfaFachadaBDR = FachadaBDR.getInstancia();

        // Recuperendo os valores
        String descricaoSubSetor = jTextField_DescricaoSetor.getText();
        int idSetor = Integer.parseInt(((KeyValue) jComboBox_idSetor.getSelectedItem()).getValue());

        // Listando as descrição produtos
        List<SubSetor> listSetor = objfaFachadaBDR.procurarSubSetorPorDescricaoPorSetor(descricaoSubSetor, idSetor);

        // Setando a tabela
        this.defTable =  atualizaLista(listSetor);

        // Setando a nova listagem
        jTable1.setModel(this.defTable);
        jTable1.revalidate();

        if(listSetor.size() > 0)
            mensagem.setText("");
        else
            mensagem.setText("Nenhuma Sub Categoria encontrada!");
    } catch (Exception ex) {
        mensagem.setText(ex.getMessage());
    }
}//GEN-LAST:event_jButton_BuscarActionPerformed

private void jButton_AtualizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_AtualizarActionPerformed
    try {
        FachadaBDR objfaFachadaBDR = FachadaBDR.getInstancia();
        // Listando os cargos
        List<SubSetor> listSubSetor = objfaFachadaBDR.listarSubSetorAtivos();

        // Setando a tabela
        this.defTable =  atualizaLista(listSubSetor);

        // Setando a nova listagem
        jTable1.setModel(this.defTable);

        // atualizando os cargos
        jTable1.revalidate();

        mensagem.setText("");
    } catch (Exception ex) {
        mensagem.setText(ex.getMessage());
    }
}//GEN-LAST:event_jButton_AtualizarActionPerformed

private void jButton_EditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_EditarActionPerformed
    int idSubSetor = 0 ;
    try {
            // pegando a linha selecionada
            if(this.jTable1.getSelectedColumnCount() == 0) throw new Exception("Favor selecionar um SubSetor");

            // Pegando a linha que está selecionada
            int linha = this.jTable1.getSelectedRow();
            // recuperando o Cpf do funcionario
            idSubSetor = (Integer) this.jTable1.getValueAt(linha,0); 

            FachadaBDR objfaFachadaBDR = FachadaBDR.getInstancia();

            SubSetor objSubSetor = objfaFachadaBDR.procurarSubSetor(idSubSetor); 
            // se a tela de cargo ja estiver instanciada
            if(!this.cadastroSubSetor.isVisible()){
                this.cadastroSubSetor = new CadSubSetor(objSubSetor.getIdSubSetor());
                this.cadastroSubSetor.setVisible(true);
            }
            // Listando os cargos
            List<SubSetor> listSubSetor = objfaFachadaBDR.listarSubSetorAtivos();

            // Setando a tabela
            this.defTable =  atualizaLista(listSubSetor);

            // Setando a nova listagem
            jTable1.setModel(this.defTable);

            // atualizando os cargos
            jTable1.revalidate();
            
            mensagem.setText("");
        } catch (Exception ex) {
            System.out.println(idSubSetor);
            mensagem.setText(ex.getMessage());
        }
}//GEN-LAST:event_jButton_EditarActionPerformed

private void jButton_RemoverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_RemoverActionPerformed
    try {
        // pegando a linha selecionada
        if(this.jTable1.getSelectedColumnCount() == 0 || this.jTable1.getSelectedColumnCount() > 1) throw new Exception("Favor selecionar um Sub Setor");

        int cancelar = JOptionPane.showConfirmDialog(null, "Deseja Remover este Sub Setor?");
        if (cancelar == JOptionPane.YES_OPTION) {
            try {
                int linha = this.jTable1.getSelectedRow();

                // recuperando o Cpf do funcionario
                int idSubSetor= (Integer) this.jTable1.getValueAt(linha,0); 

                // instanciando a fachada
                FachadaBDR objfaFachadaBDR = FachadaBDR.getInstancia();

                // Listando os cargos
                objfaFachadaBDR.removerSubSetor(idSubSetor);

                // Listando os cargos
                List<SubSetor> listSubSetor = objfaFachadaBDR.listarSubSetorAtivos();

                // Setando a tabela
                this.defTable =  atualizaLista(listSubSetor);

                // Setando a nova listagem
                jTable1.setModel(this.defTable);

                jTable1.revalidate();

                mensagem.setText("Removido com sucesso!");

            } catch (Exception ex) {
                mensagem.setText(ex.getMessage());
            }
        } 
    } catch (Exception e) {
        mensagem.setText(e.getMessage());
    }
}//GEN-LAST:event_jButton_RemoverActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(listSubSetor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(listSubSetor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(listSubSetor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(listSubSetor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new listSubSetor().setVisible(true);
            }
        });
    }
    
    public DefaultTableModel atualizaLista(List<SubSetor> listSubSetor){
        //{"#", "Descrição Sub Setor", "Setor", "QTD Maxima", "QTD Minima", "QTD Atual", "Status"}
       // Criando o objeto 
       Object [][] resposta = new Object[listSubSetor.size()][7];  
       for (int i = 0; i < resposta.length; i++){  
           
           SubSetor objSubSetor = listSubSetor.get(i);  
           resposta[i][0] = objSubSetor.getIdSubSetor();
           resposta[i][1] = objSubSetor.getDescricaoSubSetor();
           resposta[i][2] = objSubSetor.getSetor().getDescricaoSetor();
           resposta[i][3] = objSubSetor.getQuantidadeMaxima();
           resposta[i][4] = objSubSetor.getQuantidadeMinima();
           resposta[i][5] = objSubSetor.getQuantidadeArmazenada();
           resposta[i][6] = (objSubSetor.getStatusSubSetor()) ? "Ativo" : "Inativo";
        }  
        // Setando a tabela
        return new DefaultTableModel(resposta, titulos);
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton_Atualizar;
    private javax.swing.JButton jButton_Buscar;
    private javax.swing.JButton jButton_Cadastrar;
    private javax.swing.JButton jButton_Editar;
    private javax.swing.JButton jButton_Remover;
    private javax.swing.JComboBox jComboBox_idSetor;
    private javax.swing.JLabel jLabel_Nome;
    private javax.swing.JLabel jLabel_idSetor;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField_DescricaoSetor;
    private javax.swing.JLabel mensagem;
    // End of variables declaration//GEN-END:variables
}
